package com.example.config.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import com.example.config.security.domain.OauthConfig;


@Configuration
public class OauthSecurity extends AuthorizationServerConfigurerAdapter {
    
	@Autowired
    private RedisConnectionFactory connectionFactory;
	
	@Autowired
	private OauthConfig config;
	    
	 @Override
	    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
	        oauthServer.tokenKeyAccess("isAuthenticated()") // url:/oauth/token_key,exposes public key for token verification if using JWT tokens
	                   .checkTokenAccess("isAuthenticated()") //url:/oauth/check_token allow check token
	                   .allowFormAuthenticationForClients();
	    }
	 
    @Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
    	clients.inMemory()
		    	.withClient(config.getClientId())
		        .secret(config.getClientSecret())
		        .authorizedGrantTypes(config.getAuthorizedGrantTypes())
		        .scopes(config.getScope())
                .accessTokenValiditySeconds(config.getAccessTokenValiditySeconds())
//                .redirectUris(redirectUris)
                .autoApprove(config.getAutoApproveScopes());
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore());
    }
    
    @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(connectionFactory);
    }
}